package com.biubiu.firefly.wallpaper.marks;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.view.MotionEvent;
import android.view.SurfaceHolder;

import com.biubiu.firefly.R;

import java.util.Random;

public class MyWallpaperService extends WallpaperService {


    private Bitmap bitmap;

    @Override
    public Engine onCreateEngine() {
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        return new MyEngine();
    }


    class MyEngine extends  Engine{
        private boolean mVisible;
        // 记录当前用户动作发生的位置
        private float mTouchX = -1;
        private float mTouchY = -1;
        // 记录要绘制的矩形的数量
        private int count = 1;
        // 记录第一个矩形所需坐标变换的X、Y坐标的偏移
        private int originX = 250,originY = 450;
        // 定义画笔
        private Paint mPaint = new Paint();
        Handler mHandler = new Handler();

        private final Runnable drawTarget = new Runnable() {
            @Override
            public void run() {
                drawFrame();
            }
        };

        @Override
        public void onCreate(SurfaceHolder surfaceHolder) {
            super.onCreate(surfaceHolder);
            // 初始化画笔

            mPaint.setARGB(76,0,0,255);
            mPaint.setAntiAlias(true);
            mPaint.setStyle(Paint.Style.FILL);
            // 设置壁纸的触碰事件为true
            setTouchEventsEnabled(true);
        }


        @Override
        public void onVisibilityChanged(boolean visible) {
            super.onVisibilityChanged(visible);
            mVisible = visible;
            if(visible){
                drawFrame();
            }else{
                // 如果界面不可见，删除回调
                mHandler.removeCallbacks(drawTarget);
            }
        }

        //获取SurfaceHolder时调用
        @Override
        public SurfaceHolder getSurfaceHolder() {
            return super.getSurfaceHolder();
        }

        //手势移动时回调，onOffsetsChanged要注意一下，还记得有的手机滑动桌面时候背景图片会跟着左右移动吗，
        // 这个方法就可以实现这个效果，在手势滑动的每一帧都会回调依次。

        /**
         * @param xOffset x方向滑动的百分比（与桌面分页数有关）
         * @param yOffset y方向滑动百分比（一般用不到）
         * @param xOffsetStep x方向每个分页所占的百分比（1 / xOffsetStep = 桌面的分页数）
         * @param yOffsetStep 同理
         * @param xPixelOffset x放下像素偏移量
         * @param yPixelOffset 同理
         */
        @Override
        public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset) {
            super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
        }

        //Surface创建时回调
        @Override
        public void onSurfaceCreated(SurfaceHolder holder) {
            super.onSurfaceCreated(holder);
        }

        //Surface销毁时回调
        @Override
        public void onSurfaceDestroyed(SurfaceHolder holder) {
            super.onSurfaceDestroyed(holder);
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
// 删除回调
            mHandler.removeCallbacks(drawTarget);
        }

        @Override
        public void onTouchEvent(MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_MOVE){
                // 检测到滑动操作
                mTouchX = event.getX();
                mTouchY = event.getY();
            }else {
                mTouchX = -1;
                mTouchY = -1;
            }
            super.onTouchEvent(event);
        }

        private void drawFrame(){
            final SurfaceHolder holder = getSurfaceHolder();
            Canvas c = null;
            try{
                c = holder.lockCanvas();
                if(c != null){
                    c.drawColor(0xff000000);
// 在触碰点绘制图像
                    drawTouchPoint(c);
                    mPaint.setAlpha(76);
                    c.translate(originX,originY);
// 采用循环绘制count个图形
                    for(int i = 0; i < count; i++){
                        c.translate(90,0);
                        c.scale(0.95f,0.95f);
                        c.rotate(30f);
                        c.drawRect(0,0,150,75,mPaint);
                    }
                }
            }finally {
                if(c != null){
                    holder.unlockCanvasAndPost(c);
                }
            }
// 调度下一次重绘
            mHandler.removeCallbacks(drawTarget);
            if(mVisible){
                count++;
                if(count >= 50){
                    Random rand = new Random();
                    count = 1;
                    originX += (rand.nextInt(60)-30);
                    originY += (rand.nextInt(60)-30);
                }
// 每隔0.1秒执行drawTarget一次
                mHandler.postDelayed(drawTarget,100);
            }

        }

        private void drawTouchPoint(Canvas c) {

            if (mTouchX >= 0 && mTouchY >= 0) {
                // 设置画笔的透明度
                mPaint.setAlpha(255);
                if(bitmap != null)
                    c.drawBitmap(bitmap, mTouchX, mTouchY, mPaint);
            }
        }
    }
}
